02 / 13

What is an Interface? When is it used?

Difficulty: 2/10

Interface

An interface defines a contract that implementing types agree to satisfy. It focuses primarily on what an object can do rather than how it stores or implements that behavior. Interfaces are valuable for loose coupling, dependency injection, multiple capabilities, testability and substituting implementations. For example, an application can depend on a PaymentGateway interface while different implementations support Stripe, Razorpay, a bank gateway or a test fake.

javascript
  1. 1

    Defines a contract or capability.

  2. 2

    Reduces dependency on concrete implementations.

  3. 3

    Supports multiple implementations.

  4. 4

    Works naturally with dependency injection.

  5. 5

    Improves unit testing by allowing test doubles.

  6. 6

    The exact capabilities of interfaces vary between languages.

Follow-up Questions

  • Can an interface contain implementation?
  • Can a class implement multiple interfaces?
  • How does dependency injection use interfaces?
  • What is the difference between an interface and an abstract class?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.